package com.bjb.vr.monitor.util;

import com.bjb.vr.common.utils.DateTimeUtil;
import com.bjb.vr.monitor.ao.StatusAlarmAo;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;

/**
 * @description: 服务上线下线报警工具类
 * @author: HuJingBo
 * @time: 2022/3/16 18:56
 */
@Slf4j
public class ServiceStatusSender {

    private ServiceStatusSender() {
    }

    /**
     * 发送钉钉消息
     *
     * @param alarmAo
     * @param title
     */
    public static void sendDingDingMsg(StatusAlarmAo alarmAo, String title) {
        try {
            StringBuilder alarmMsg = new StringBuilder("## ").append(title).append("\n");
            alarmMsg.append("- 服务名称： ").append(alarmAo.getServiceName()).append("\n")
                    .append("- 服务节点ID：").append(alarmAo.getServiceAgentId()).append("\n")
                    .append("- 服务IP：").append(alarmAo.getServiceIP()).append("\n")
                    .append("- 服务端口：").append(alarmAo.getServicePort()).append("\n")
                    .append("- 服务状态：").append(alarmAo.getServiceStatus()).append("\n")
                    .append("- 当前实例总数：").append(alarmAo.getInstanceSum()).append("\n")
                    .append("- 告警时间：").append(DateTimeUtil.timeStampToDateStr(alarmAo.getStartTime())).append("\n");
            DingDingUtil.sendMsg(DingDingUtil.SERVER_STATUS_ALARM, title, alarmMsg.toString(), null);
            log.info("钉钉告警消息已发送...");
        } catch (Exception e) {
            log.error("钉钉告警消息发送失败,{}", e);
        }
    }

    /**
     * 发送邮件消息
     *
     * @param alarmAo
     * @param emailUtil
     * @param mailReceivers
     * @param title
     */
    public static void sendEmailMsg(StatusAlarmAo alarmAo, EmailUtil emailUtil, List<String> mailReceivers, String title) {
        try {
            HashMap<String, Object> params = new HashMap<>();
            params.put("title", title);
            params.put("serviceName", alarmAo.getServiceName());
            params.put("serviceAgentId", alarmAo.getServiceAgentId());
            params.put("serviceIP", alarmAo.getServiceIP());
            params.put("servicePort", alarmAo.getServicePort());
            params.put("serviceStatus", alarmAo.getServiceStatus());
            params.put("instanceSum", alarmAo.getInstanceSum());
            params.put("startTime", DateTimeUtil.timeStampToDateStr(alarmAo.getStartTime()));
            emailUtil.sendTemplateMail(mailReceivers.stream().toArray(String[]::new), title, params, "statusAlarmMail.html");
            log.info("告警邮件已发送...");
        } catch (Exception e) {
            log.error("告警邮件发送失败,{}", e);
        }
    }
}
